<template>
  <mu-container>
    <mu-form :model="form" label-position="top" label-width="100">
      <mu-form-item prop="username" label="用户名">
        <mu-text-field v-model="form.username"></mu-text-field>
      </mu-form-item>
      <mu-form-item prop="password" label="密码">
        <mu-text-field v-model="form.password" type="password" autocomplete="off"></mu-text-field>
      </mu-form-item>
    </mu-form>
    <mu-button color="primary" @click="handleLogin()">登录</mu-button>
  </mu-container>
</template>

<script>
import { mapGetters, mapActions } from 'vuex'

export default {
  name: 'Login',
  data() {
    return {
      form: {
        username: '',
        password: ''
      }
    }
  },
  computed: {
    ...mapGetters({
      userInfo: 'auth/userInfo'
    })
  },
  watch: {
    userInfo() {
      this.checkLogin()
    }
  },
  created() {
    this.checkLogin()
  },
  methods: {
    ...mapActions({
      login: 'auth/login'
    }),
    checkLogin() {
      if (this.userInfo) {
        this.$toast.info('你已经登录')
        this.$router.push({ name: 'Home' })
      }
    },
    async handleLogin() {
      try {
        await this.login(this.form)
        this.$toast.success('登录成功')
        this.$router.push({ name: 'Home' })
      } catch (err) {
        this.$report(err)
      }
    }
  }
}
</script>
